package com.ukao.steward.ui.valetRunners.storage;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ukao.steward.R;
import com.ukao.steward.adapter.FactortTabFragmentAdapter;
import com.ukao.steward.base.BaseFragment;
import com.ukao.steward.bean.AddClothingItem;
import com.ukao.steward.bean.StorageListBean;
import com.ukao.steward.bean.StoreBean;
import com.ukao.steward.bean.StringBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.dialog.PopWindowHelp;
import com.ukao.steward.eventbus.AddClothingEvent;
import com.ukao.steward.eventbus.AppEvent;
import com.ukao.steward.listener.MyOnPageChangeListener;
import com.ukao.steward.retrofit.ApiCallback;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.DecimalUtil;
import com.ukao.steward.util.L;
import com.ukao.steward.util.T;
import com.ukao.steward.widget.CustomPopWindow;
import com.ukao.steward.widget.NoScrollViewPager;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import me.yokeyword.fragmentation.SupportFragment;
import rx.Observable;

import static com.ukao.steward.consts.Constant.ADDITIONAL_SERVICES_EIGHT;
import static com.ukao.steward.consts.Constant.ADJUNCT_THREE;
import static com.ukao.steward.consts.Constant.ARG_PARAM3;
import static com.ukao.steward.consts.Constant.BRAND_SEVEN;
import static com.ukao.steward.consts.Constant.CLOTHING_ONE;
import static com.ukao.steward.consts.Constant.COLORS_FOUR;
import static com.ukao.steward.consts.Constant.EFFECT_SIX;
import static com.ukao.steward.consts.Constant.FLAW_FIVE;
import static com.ukao.steward.consts.Constant.PROJECT_ZERO;
import static com.ukao.steward.consts.Constant.SERVE_TWO;


public class AddClothingFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.view_pager)
    NoScrollViewPager mViewPager;
    Unbinder unbinder;
    @BindView(R.id.arrow_tv)
    TextView arrowTv;
    @BindView(R.id.left_tv)
    TextView leftTv;
    @BindView(R.id.right_tv)
    TextView rightTv;
    @BindView(R.id.back_tv)
    TextView backTv;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.finish_storage_tv)
    TextView finishStorageTv;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    private int pagePosition;
    private int isCustomNum;
    private String unitText = "";

    private String orderId = "";
    private String businessName;
    private String proTypeId = "";
    private String proServiceId = "";
    private String serviceName = "";
    private String count = "";
    private String brandId = "";
    private String brandName = "";

    private String flcardDiscount;
    private String colorDesc = "";
    private String flawDesc = "";
    private String effectDesc = "";
    private String addServiceDesc = "";
    private String annexDesc = "";
    private String totalMoney = "";

    private String businessId9 = "";
    private String businessId4 = "";
    private String chgSubtotal = "";
    private String projectId;
    private String businessId;
    private boolean firstUpdate;
    private FactortTabFragmentAdapter mTabFragment;
    private List<StringBean> mAnnexDesclist, mColorDesclist, mflawDesclist, meffectDesclist, mServiceDesclist;
    private String[] clothingArray;
    private List<StoreBean> mArrowData;
    private CustomPopWindow mCustomPopWindow;
    private String clothingId;
    StorageListBean.ProListBean mProListBean;
    private int sortNo;

    public static AddClothingFragment newInstance(String orderId, StorageListBean.ProListBean mProListBean, int sortNo) {
        AddClothingFragment fragment = new AddClothingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, orderId);
        args.putParcelable(ARG_PARAM2, mProListBean);
        args.putInt(ARG_PARAM3, sortNo);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            orderId = getArguments().getString(ARG_PARAM1);
            mProListBean = getArguments().getParcelable(ARG_PARAM2);
            sortNo = getArguments().getInt(ARG_PARAM3, 0);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_add_clothing, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    protected void initView() {

        mArrowData = new ArrayList<>();
        clothingArray = getResources().getStringArray(R.array.clothing_array);
        for (int i = 0; i < clothingArray.length; i++) {
            String s = clothingArray[i];
            if (CheckUtils.isNull(mProListBean)) {
                mArrowData.add(new StoreBean(s, false));
            } else {
                mArrowData.add(new StoreBean(s, true));
            }

        }
        if (mProListBean != null) {
            rightTv.setText(clothingArray[1]);
            rightTv.setVisibility(View.VISIBLE);
            Gson mGson = new Gson();
            if (!CheckUtils.isEmpty(mProListBean.getAddServiceDesc())) {
                mServiceDesclist = mGson.fromJson(mProListBean.getAddServiceDesc(),
                        new TypeToken<List<StringBean>>() {
                        }.getType());
            }

            if (!CheckUtils.isEmpty(mProListBean.getAnnexDesc())) {
                mAnnexDesclist = mGson.fromJson(mProListBean.getAnnexDesc(),
                        new TypeToken<List<StringBean>>() {
                        }.getType());


            }
            if (!CheckUtils.isEmpty(mProListBean.getColorDesc())) {
                mColorDesclist = mGson.fromJson(mProListBean.getColorDesc(),
                        new TypeToken<List<StringBean>>() {
                        }.getType());

            }
            if (!CheckUtils.isEmpty(mProListBean.getFlawDesc())) {
                mflawDesclist = mGson.fromJson(mProListBean.getFlawDesc(),
                        new TypeToken<List<StringBean>>() {
                        }.getType());

            }
            if (!CheckUtils.isEmpty(mProListBean.getEffectDesc())) {
                meffectDesclist = mGson.fromJson(mProListBean.getEffectDesc(),
                        new TypeToken<List<StringBean>>() {
                        }.getType());

            }

            businessId = mProListBean.getBusinessId() + "";  /*项目的businessId*/
            businessName = mProListBean.getBusinessName();/*项目名称*/
            projectId = mProListBean.getMercBusinessId();/*项目id*/
            clothingId = mProListBean.getProductId() + "";/*衣物详情列表id*/
            proTypeId = mProListBean.getProTypeId() + "";/*衣物详情列表tab*/
            count = CheckUtils.isNull(mProListBean.getCount()) ? "" : mProListBean.getCount() + "";/*服务数量*/
            serviceName = mProListBean.getServiceName();/*服务名称*/
            proServiceId = mProListBean.getProServiceId() + "";/*服务id*/
            brandId = mProListBean.getBrandId();/*品牌id*/
            brandName = mProListBean.getBrandName();/*品牌*/
            chgSubtotal = mProListBean.getChgSubtotal();
            if (!CheckUtils.isEmpty(mProListBean.getColorDesc()))
                colorDesc = mProListBean.getColorDesc();  /*颜色*/
            if (!CheckUtils.isEmpty(mProListBean.getAnnexDesc()))
                annexDesc = mProListBean.getAnnexDesc();/*附件*/
            if (!CheckUtils.isEmpty(mProListBean.getFlawDesc()))
                flawDesc = mProListBean.getFlawDesc();/*瑕疵*/
            if (!CheckUtils.isEmpty(mProListBean.getEffectDesc()))
                effectDesc = mProListBean.getEffectDesc();/*洗后效果*/
            if (!CheckUtils.isEmpty(mProListBean.getAddServiceDesc()))
                addServiceDesc = mProListBean.getAddServiceDesc();/*附加服务*/
                isCustomNum = mProListBean.getIsCustomNum();
                unitText = mProListBean.getProductUnitText();
        }
        List<SupportFragment> mFragmentData = new ArrayList<>();
        mFragmentData.add(AddClothingChildFragment.createBuilder().isSinge(true).enterPos(PROJECT_ZERO).setDefaultMatchCheck(businessId).build());
        mFragmentData.add(AddClothingChildFragment.createBuilder().isSinge(true).isEnabledKeyboard(true).isEnabledAdd(false).isEnabledSearch(true)
                .orderId(orderId).setDefaultMatchCheck(clothingId).productId(projectId).enterPos(CLOTHING_ONE).build());
        AddClothingChildFragment mFragment2 = AddClothingChildFragment.createBuilder().isSinge(true)
                .orderId(orderId).productId(clothingId).isCustomNum(isCustomNum).unitText(unitText).setDefaultMatchCheck(proServiceId).enterPos(SERVE_TWO).build();
        mFragmentData.add(mFragment2);
        mFragmentData.add(AddClothingChildFragment.createBuilder().isEnabledAdd(true).productId(businessId).isEnabledSearch(false).enterPos(ADJUNCT_THREE).setDefaultMoreMatchCheck(mAnnexDesclist).build());
        mFragmentData.add(AddClothingChildFragment.createBuilder().isSinge(true).isEnabledKeyboard(true).isEnabledSearch(true).isEnabledAdd(true).enterPos(COLORS_FOUR).setDefaultMoreMatchCheck(mColorDesclist).build());
        mFragmentData.add(AddClothingChildFragment.createBuilder().isSinge(false).isEnabledKeyboard(true).isEnabledSearch(true).isEnabledAdd(true).enterPos(FLAW_FIVE).setDefaultMoreMatchCheck(mflawDesclist).build());
        mFragmentData.add(AddClothingChildFragment.createBuilder().isEnabledKeyboard(true).isEnabledAdd(true).isEnabledSearch(true).enterPos(EFFECT_SIX).setDefaultMoreMatchCheck(meffectDesclist).build());
        mFragmentData.add(AddClothingChildFragment.createBuilder().isSinge(true).isEnabledKeyboard(true).isEnabledAdd(true).isEnabledSearch(true).setDefaultMatchCheck(brandId).enterPos(BRAND_SEVEN).build());
        mFragmentData.add(AddClothingChildFragment.createBuilder().isEnabledAdd(true).enterPos(ADDITIONAL_SERVICES_EIGHT).productId(businessId).setDefaultMoreMatchCheck(mServiceDesclist).build());
        mTabFragment = new FactortTabFragmentAdapter(getChildFragmentManager(), mFragmentData);
        mViewPager.setAdapter(mTabFragment);
        mViewPager.setOffscreenPageLimit(mFragmentData.size() - 1);

    }

    @Override
    protected void initListener() {
        super.initListener();
        mViewPager.addOnPageChangeListener(new MyOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                pagePosition = position;
                arrowTv.setText((clothingArray[position]));
                if (position != 0) {
                    leftTv.setText(clothingArray[position - 1]);
                    leftTv.setVisibility(View.VISIBLE);

                } else {
                    leftTv.setVisibility(View.GONE);
                    leftTv.setText(clothingArray[position]);
                }
                if (position != 8 && mArrowData.get(position).isSelect()) {
                    rightTv.setText(clothingArray[position + 1]);
                    rightTv.setVisibility(View.VISIBLE);

                } else {
                    rightTv.setVisibility(View.GONE);
                }


            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.left_tv, R.id.right_tv, R.id.arrow_tv, R.id.finish_storage_tv, R.id.back_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.finish_storage_tv:
                finishStorage();
                break;
            case R.id.back_tv:
                finish();
                break;
            case R.id.left_tv:
                int currentPos = mViewPager.getCurrentItem();
                if (currentPos != 0)
                    mViewPager.setCurrentItem(currentPos - 1);
                break;
            case R.id.right_tv:
                int currentPos1 = mViewPager.getCurrentItem();
                if (currentPos1 != 8)
                    mViewPager.setCurrentItem(currentPos1 + 1);
                break;
            case R.id.arrow_tv:
                String str = getText(arrowTv);
                for (StoreBean storeBean : mArrowData) {
                    if (storeBean.getName().equals(str)) {
                        storeBean.setCheck(true);
                    } else {
                        storeBean.setCheck(false);
                    }
                }

                mCustomPopWindow = PopWindowHelp.showPopStoreList(arrowTv, _mActivity, mArrowData, position -> {
                    StoreBean mItem = mArrowData.get(position);
                    boolean isSelect = true;
                    if (position != 0) {
                        StoreBean mPerItem = mArrowData.get(position - 1);
                        isSelect = mPerItem.isSelect();
                    }
                    if (mItem != null && isSelect) {
                        if (mItem.isCheck()) return;
                        mCustomPopWindow.dissmiss();
                        mViewPager.setCurrentItem(position, false);
                        mItem.setCheck(true);
                        for (int i = 0; i < mArrowData.size(); i++) {
                            StoreBean storeBean = mArrowData.get(i);
                            if (position != i) {
                                storeBean.setCheck(false);
                            }
                        }
                        arrowTv.setText(CheckUtils.isEmptyString(mItem.getName()));


                    } else {
                        warmPrompt();

                    }


                });
                break;
        }
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(AppEvent event) {
        switch (event.getMessage()) {
            case update:
                AddClothingItem mItem = (AddClothingItem) event.getData();
                if (mItem == null) return;
                receiveData(mItem, mItem.getEnterPos());
                break;
        }

    }

    /**
     * 接收数据
     * @param item
     * @param pos
     */
    public void receiveData(AddClothingItem item, int pos) {
        switch (pos) {
            case PROJECT_ZERO:
                Log.d("触发了", "receiveData:");
                projectId = "";
                businessId = "";
                clothingId = "";
                businessName = "";
                projectId = item.getId();
                businessId = item.getBusinessId();
                businessName = item.getName();
                cleanRequestParameter( false);
                AddClothingChildFragment mFragment1 = (AddClothingChildFragment) mTabFragment.getItem(1);
                if (mFragment1 != null) {
                    mFragment1.setProductId(projectId, false);
                    if (item.isSinge())
                        mViewPager.setCurrentItem(1, false);
                }
                break;
            case CLOTHING_ONE:
                cleanRequestParameter( true);
                proTypeId = item.getTypeId();
                AddClothingChildFragment mFragment2 = (AddClothingChildFragment) mTabFragment.getItem(2);
                if (mFragment2 != null) {
                    title.setText(item.getName());
                    clothingId = item.getId();
                    isCustomNum = item.getIsCustomNum();
                    unitText = item.getUnitText();

                    mFragment2.setProductIdUnit(clothingId, isCustomNum, unitText, false, "");
                    if (item.isSinge())
                        mViewPager.setCurrentItem(2, false);

                }

                break;
            case SERVE_TWO:
                proServiceId = "";
                serviceName = "";
                count = "";
                proServiceId = item.getId();
                serviceName = item.getName();
                count = DecimalUtil.multiply(item.getCount());
                for (StoreBean storeBean : mArrowData) {
                    storeBean.setEnabled(true);
                    storeBean.setSelect(true);
                }
                AddClothingChildFragment mFragment3 = (AddClothingChildFragment) mTabFragment.getItem(3);
                if (mFragment3 != null){
                    mFragment3.setProductId(businessId, false);
                }
                AddClothingChildFragment mFragment8 = (AddClothingChildFragment) mTabFragment.getItem(8);
                if (mFragment8 != null) mFragment8.setProductId(businessId, false);
                if (item.isSinge())
                    mViewPager.setCurrentItem(3, false);
                break;
            case ADJUNCT_THREE:

                annexDesc = item.getSelectDesc();


                break;
            case COLORS_FOUR:
                JSONArray mJSONArray = new JSONArray();
                JSONObject mJSONObject = new JSONObject();
                try {
                    mJSONObject.put("id", item.getId());
                    mJSONObject.put("name", item.getName());
                    mJSONArray.put(mJSONObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                colorDesc = mJSONArray.toString();
                if (item.isSinge())
                    mViewPager.setCurrentItem(5, false);

                break;
            case FLAW_FIVE:
                flawDesc = item.getSelectDesc();

                break;
            case EFFECT_SIX:
                effectDesc = item.getSelectDesc();

                break;
            case BRAND_SEVEN:

                brandId = item.getId();
                brandName = item.getName();
                if (item.isSinge()) {
                    AddClothingChildFragment mFragment8s = (AddClothingChildFragment) mTabFragment.getItem(8);
                    if (mFragment8s != null) mFragment8s.setProductId(businessId, false);
                    mViewPager.setCurrentItem(8, false);
                }

                break;
            case ADDITIONAL_SERVICES_EIGHT:
                addServiceDesc = item.getSelectDesc();

                break;

        }


    }

    /**
     * 清楚数据
     *
     *
     * @param isSelectClothing 是否勾选了衣物
     */
    private void cleanRequestParameter(boolean isSelectClothing) {
       /*清除衣物*/

        unitText = "";
        proTypeId = "";
        clothingId = "";
        unitText = "";
        isCustomNum = 0;

        title.setText("入库");
        /*清除服务*/
        proServiceId = "";
        serviceName = "";
        count = "";
        /*清除附件*/
        annexDesc = "";

        /*清除附加*/

        addServiceDesc = "";
        /*清除金额*/
        chgSubtotal = "";
        /*清除颜色*/
        colorDesc = "";

        /*清楚瑕疵*/
        flawDesc = "";

        /*清除洗后效果*/
        effectDesc = "";

        /*附件服务*/
        addServiceDesc = "";
        /*清楚品牌*/
        brandName = "";
        brandId = "";
        businessId4 = "";
        businessId9 = "";
        firstUpdate = true;
        for (int i = 0; i < mArrowData.size(); i++) {
            StoreBean storeBean = mArrowData.get(i);
            if (0 == i || isSelectClothing && i == 1) {
                storeBean.setSelect(true);
            } else {
                storeBean.setSelect(false);
            }


        }


        AddClothingEvent.postHasData(AddClothingEvent.Message.unselect, isSelectClothing);
    }

    /**
     * 完成入库
     */
    private void finishStorage() {
        if (warmPrompt()) return;

        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("orderId", orderId);
        mHashMap.put("businessId", businessId);/*项目的businessId*/
        mHashMap.put("mercBusinessId", projectId);/*项目id*/
        mHashMap.put("businessName", businessName);/*项目名称*/
        mHashMap.put("productId", clothingId);/*衣物详情列表id*/
        mHashMap.put("proTypeId", proTypeId);/*衣物详情列表tab*/
        mHashMap.put("count", count);/*服务数量*/
        mHashMap.put("serviceName", serviceName);/*服务名称*/
        mHashMap.put("proServiceId", proServiceId);/*服务id*/
        mHashMap.put("brandId", brandId);/*品牌id*/
        mHashMap.put("brandName", brandName);/*品牌*/
        mHashMap.put("sortNo", sortNo + "");
        if (!CheckUtils.isEmpty(chgSubtotal)) {
            mHashMap.put("chgSubtotal", chgSubtotal);/*修改金额*/
        }
        if (!CheckUtils.isEmpty(colorDesc)) mHashMap.put("colorDesc", colorDesc);  /*颜色*/
        if (!CheckUtils.isEmpty(annexDesc)) mHashMap.put("annexDesc", annexDesc);/*附件*/
        if (!CheckUtils.isEmpty(flawDesc)) mHashMap.put("flawDesc", flawDesc);/*瑕疵*/
        if (!CheckUtils.isEmpty(effectDesc)) mHashMap.put("effectDesc", effectDesc);/*洗后效果*/
        if (!CheckUtils.isEmpty(addServiceDesc)) mHashMap.put("addServiceDesc", addServiceDesc);/*附加服务*/
        if (!CheckUtils.isNull(mProListBean))
            mHashMap.put("id", mProListBean.getId() + "");
        mHashMap.put("accessToken", SaveParams.getToken());

        L.i("mHashMap=" + mHashMap.toString());
        stockInUpdate(!CheckUtils.isNull(mProListBean), mHashMap);

    }

    private boolean warmPrompt() {
        if (CheckUtils.isEmpty(businessName)) {

            T.show("请选择项目");
            return true;
        } else if (CheckUtils.isEmpty(clothingId)) {
            T.show("请选择衣物");
            return true;
        } else if (CheckUtils.isEmpty(serviceName)) {
            T.show("请选择服务");
            return true;
        }
        return false;
    }

    public void stockInUpdate(boolean isStockInUpdate, HashMap mHashMap) {
        showProgressDialog();
        Observable observable = null;
        if (isStockInUpdate) {
            observable = apiStores().stockInUpdate(Constant.createParameter(mHashMap));
        } else {
            observable = apiStores().finishstockIn(Constant.createParameter(mHashMap));
        }
        addSubscription(observable,
                new ApiCallback<StringBean>() {
                    @Override
                    public void onSuccess(StringBean model) {
                        if (model.getHttpCode() == 200) {
                            dismissProgressDialog();
                            setFragmentResult(RESULT_OK, null);
                            finish();

                        } else {
                            T.show(model.getMsg());

                        }


                    }


                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }

                });
    }


}
